package com.example.onlineeducation.ui.online

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.onlineeducation.App
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.databinding.OnlineExaminationAcBinding
import com.example.onlineeducation.ui.mine.ExamRecordActivity
import com.example.onlineeducation.ui.mine.ExamResultDetailActivity
import com.example.onlineeducation.utils.ProblemAdapterUtil
import com.example.onlineeducation.utils.YcLoopCountDown
import com.example.onlineeducation.utils.YcTimeUtils
import com.example.onlineeducation.viewmodel.OnlineExaminationAcVM
import com.yc.jetpacklib.extension.ycIsEmpty
import com.yc.jetpacklib.net.doFail
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.utils.YcTime
import com.yc.jetpacklib.widget.dialog.YcCommonDialog

/**
 * Creator: yc
 * Date: 2022/4/21 10:10
 * UseDes:线上考试
 */
@SuppressLint("SetTextI18n")
class OnlineExaminationAc : BaseActivity<OnlineExaminationAcBinding>(OnlineExaminationAcBinding::inflate) {
    companion object {
        private const val KEY_EXAMINATION_ID = "key_examination_id"
        private const val KEY_EXAMINATION_NAME = "key_examination_name"
        private const val KEY_EXAMINATION_TOTAL_TIME = "key_examination_total_time"
        private const val KEY_EXAMINATION_TIME_END = "key_examination_time"

        /**
         *
         * @param examinationId String?     考试的id
         * @param examinationName String    考试名称
         * @param examinationTime Int       考试总时长(分钟)
         * @param examinationTimeEnd String 考试最晚结束时间(格式"yyyy-MM-dd HH:mm:ss")
         * @param proId String 项目ID
         */
        @JvmStatic
        fun newInstance(context: Context, examinationId: String?, examinationName: String, examinationTime: Int, examinationTimeEnd: String) {
            context.startActivity(Intent(context, OnlineExaminationAc::class.java).apply {
                putExtra(KEY_EXAMINATION_ID, examinationId)
                putExtra(KEY_EXAMINATION_NAME, examinationName)
                val examinationTimeMillisecond = examinationTime * 60 * 1000L
                putExtra(KEY_EXAMINATION_TOTAL_TIME, examinationTimeMillisecond)
                val timeEnd = YcTime.stringToCalendar(examinationTimeEnd, YcTime.FORMAT_TIME_SECOND).time.time
                putExtra(KEY_EXAMINATION_TIME_END, timeEnd)
            })
        }
    }

    private val mViewModel by ycViewModels<OnlineExaminationAcVM>()
    private lateinit var mExaminationId: String
    private lateinit var mExaminationName: String

    /**
     * 考试时长（毫秒）
     */
    private var mExaminationTime: Long = 0

    /**
     * 考试设定结束时间(毫秒)
     */
    private var mExaminationTimeEnd: Long = 0L
    private lateinit var mProId: String
    private lateinit var mLaunchDetail: ActivityResultLauncher<Intent>
    private val mProblemUtil by lazy { ProblemAdapterUtil() }
    private val mTimeCountDown: YcLoopCountDown by lazy {
        YcLoopCountDown(this).apply {
            mPeriodTime = 1000
            mPost.observe {
                if (it < 0) {
                    mViewBinding.tvCountDownTime.text = "剩余时间：0分0秒"
                    mDialog.setMsg("时间已到，请提交考试")
                        .setSingleBtnText("提交")
                        .setSingleOnClick {
                            mViewModel.finishExamination(mProId, mExaminationId, mProblemUtil.getData())
                        }.showSingle()
                    mTimeCountDown.finish()
                } else {
                    mViewBinding.tvCountDownTime.text = "剩余时间：${it / 1000 / 60}分${it / 1000 % 60}秒"
                }
            }
        }
    }

    override fun OnlineExaminationAcBinding.initView() {
        intent.apply {
            mExaminationId = getStringExtra(KEY_EXAMINATION_ID)!!
            mExaminationName = getStringExtra(KEY_EXAMINATION_NAME)!!
            mExaminationTime = getLongExtra(KEY_EXAMINATION_TOTAL_TIME, 0L)
            mExaminationTimeEnd = getLongExtra(KEY_EXAMINATION_TIME_END, 0L)
            actionBar.setTitle(mExaminationName)
        }
        App.mInstant.mViewModel.mProInfoEntity.observe {
            mProId = it!!.proId
        }
        mLaunchDetail = ExamResultDetailActivity.getLauncher(this@OnlineExaminationAc) {
            if (it) {
                resetData()
            } else {
                finish()
            }
        }
        rvProblem.layoutManager = object : LinearLayoutManager(this@OnlineExaminationAc, HORIZONTAL, false) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        mProblemUtil.mProblemNumCall = { currentPosition: Int, itemCount: Int ->
            ivCountDownProblemNum.text = "第${currentPosition + 1}/${itemCount}题"
            if (itemCount == 1) {
                tvBeforeProblem.isVisible = false
                tvNextProblem.isVisible = false
                tvFinishProblem.isVisible = true
            } else {
                when (currentPosition) {
                    0 -> {
                        tvBeforeProblem.isVisible = false
                        tvNextProblem.isVisible = true
                        tvFinishProblem.isVisible = false
                    }
                    itemCount - 1 -> {
                        tvBeforeProblem.isVisible = true
                        tvNextProblem.isVisible = false
                        tvFinishProblem.isVisible = true
                    }
                    else -> {
                        tvBeforeProblem.isVisible = true
                        tvNextProblem.isVisible = true
                        tvFinishProblem.isVisible = false
                    }
                }
            }
        }
        mProblemUtil.initRecyclerView(rvProblem)
        tvBeforeProblem.setOnClickListener {
            mProblemUtil.before()
        }
        tvNextProblem.setOnClickListener {
            mProblemUtil.next()
        }
        tvFinishProblem.setOnClickListener {
            mProblemUtil.checkFinishCall {
                mDialog.setMsg("是否完成考试")
                    .setRightBtnText("完成")
                    .setLeftBtnText("返回")
                    .setOnRightClick {
                        mViewModel.finishExamination(mProId, mExaminationId, mProblemUtil.getData())
                    }.show()
            }
        }
        mViewModel.apply {
            mFinishExamination.observe {
                it.doSuccess {
                    mTimeCountDown.finish()
                    ExamResultDetailActivity.newInstanceExamResult(this@OnlineExaminationAc, it.examLogId ?: "", mExaminationName, mLaunchDetail)
                }.doFail {
                    mDialog.setMsg("提交失败:${it.msg}")
                        .setLeftBtnText("退出")
                        .setOnLeftClick {
                            finish()
                        }
                        .setRightBtnText("重试")
                        .setOnRightClick {
                            mViewModel.finishExamination(mProId, mExaminationId, mProblemUtil.getData())
                        }.show()
                }
            }
            mGetExaminationProblemList.observe {
                it.doSuccess {
                    if (it.ycIsEmpty()) {
                        mDialog.setMsg("暂无考试题目")
                            .setSingleBtnText("返回")
                            .setSingleOnClick {
                                finish()
                            }.show()
                    } else {
                        val currentTime = System.currentTimeMillis()
                        val surplus = mExaminationTimeEnd - currentTime
                        if (surplus > mExaminationTime) {
                            mTimeCountDown.mTotalTime = mExaminationTime
                        } else {
                            mTimeCountDown.mTotalTime = surplus
                        }
                        mTimeCountDown.resetStart()
                        mProblemUtil.addAll(it)
                    }
                }.doFail {
                    mDialog.setMsg("获取题目失败:${it.msg}")
                        .setSingleBtnText("返回")
                        .setSingleOnClick {
                            finish()
                        }.show()
                }
            }
        }
        resetData()
    }

    private fun resetData() {
        val currentTime = System.currentTimeMillis()
        mProblemUtil.reset()
        if (currentTime > mExaminationTimeEnd) {
            mDialog.setMsg("考试已结束")
                .setSingleBtnText("退出")
                .setSingleOnClick {
                    finish()
                }.showSingle()
        } else {
            mViewModel.getExaminationProblemList(mExaminationId)
        }
    }
}